package com.example.tourism.config;

import com.example.tourism.utils.TokenUtil;
import jakarta.servlet.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

// 不使用
public class AuthFilter implements Filter {
    private static final List<String> WHITE_LIST_URLS = Arrays.asList(
            // 可以根据需要添加更多URL（白名单）
            "/user/login"
            ,"/user/register"
            , "/user/checkVerifyCode"
            ,"/user/sendEmail"

    );
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        System.out.println("到了过滤器");
        httpResponse.setContentType("application/json;charset=utf-8");
        httpRequest.setCharacterEncoding("utf-8");

        String accessToken = httpRequest.getHeader("Authorization");
        String requestURI = httpRequest.getRequestURI();

        if (WHITE_LIST_URLS.contains(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        System.out.println("accessToken: " + accessToken);
        if (accessToken != null && accessToken.startsWith("Bearer ")) {
            accessToken = accessToken.substring(7);
            try {
                System.out.println("开始验证accessToken");
                if (TokenUtil.verifyToken(accessToken)) {
                    String Id = TokenUtil.getId(accessToken);
                    httpRequest.setAttribute("Id", Id);
                    System.out.println("accessToken验证通过，继续执行逻辑");
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    System.out.println("accessToken验证失败");
                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpResponse.getWriter().write("拦截器中出现错误");
                }
            } catch (Exception e) {
                System.out.println("accessToken过期");
                e.printStackTrace();
                httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                httpResponse.getWriter().write("Internal Server Error");
            }
        } else {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            System.out.println("accessToken为空");
            httpResponse.getWriter().write("没有被允许访问!");
        }
    }


}


